package www.dianbaozu.com.ui.login

import android.os.Bundle
import android.view.View
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.netease.nim.uikit.xpopup.CreateXPopupHelper
import com.netease.nim.uikit.xpopup.PopupViewEntity
import dagger.hilt.android.AndroidEntryPoint
import www.dianbaozu.com.R
import www.dianbaozu.com.databinding.FragmentRegisteBinding
import www.dianbaozu.com.ui.ProxyViewModel
import www.wen.com.common.lib.base.fragment.BaseReceiveSMSFragment
import www.wen.com.common.lib.base.module.BaseViewModel
import www.wen.com.common.lib.data.entities.ContractEntity
import www.wen.com.common.lib.data.entities.RequestRegisterBody
import www.wen.com.common.lib.data.entities.RequestVerifyBody
import www.wen.com.common.lib.extension.*
import www.wen.com.common.lib.helper.loading.KeyHelper
import www.wen.com.common.lib.helper.loading.KeyHelper.MMKV_ITAC
import www.wen.com.common.lib.helper.loading.KeyHelper.REGISTE_REMAINDER_TIME
import www.wen.com.common.lib.helper.loading.TitleBarUniversalAdapter
import www.wen.com.common.lib.util.MD5Util
import www.wen.com.common.lib.util.SpUtil

/**
 * @author WEN
 * @Description:注册页面
 * @date 2020//25 17:48
 */
@AndroidEntryPoint
class RegisteFragment : BaseReceiveSMSFragment<FragmentRegisteBinding>(), View.OnClickListener {

    private val registeViewModel: RegisteViewModel by viewModels()

    private val proxyViewModel: ProxyViewModel by activityViewModels()

    override val viewModel: BaseViewModel
        get() = registeViewModel

    override fun getLayoutId(): Int = R.layout.fragment_registe

    override fun isEnableLoadingHelper() = true

    override fun getTitleBarUniversalAdapter(): TitleBarUniversalAdapter = TitleBarUniversalAdapter(
            requireActivity(),
            action = ::titleAction
    )

    override fun getRecordTimeKey(): String = REGISTE_REMAINDER_TIME

    override fun getSystemRecordTimeKey(): String = KeyHelper.REGISTE_SYSTEM_REMAINDER_TIME

    override fun uncalibratedTime(){
        registeViewModel.mEnabledSubmit.value = false
    }

    override fun initializeInCountBackwards(){
        registeViewModel.mEnabledSubmit.value = true
    }

    override fun lazyInitView() {
        super.lazyInitView()
        dataBinding.proxyViewModel = proxyViewModel
        dataBinding.registeViewModel = registeViewModel
        dataBinding.slSelectContainer.post {
            dataBinding.slSelectContainer.isSelected = false
        }
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.slVerificationCode -> {
                sendVerificationCode()
            }

            R.id.tvRegiste -> {
                requestRegister()
            }

            R.id.tvCountryAreaCode -> {
                showAreaPopupView()
            }
            R.id.strUserAgreement -> {
                nav(R.id.action_registeFragment_to_contractFragment, args = Bundle().apply {
                    putParcelable(KeyHelper.BUNDLE_DATA, ContractEntity("用户协议", "用户协议"))
                })
            }
            R.id.strPrivacyAgreement -> {
                nav(R.id.action_registeFragment_to_contractFragment, args = Bundle().apply {
                    putParcelable(KeyHelper.BUNDLE_DATA, ContractEntity("隐私政策", "隐私政策"))
                })
            }
            R.id.AgreeAgreement -> {
                dataBinding.slSelectContainer.isSelected = !dataBinding.slSelectContainer.isSelected
                registeViewModel.mAgree.set(dataBinding.slSelectContainer.isSelected)
                registeViewModel.switchEnabledSubmit("")
            }
        }
    }

    /**
     * 注册并登陆
     */
    private fun requestRegister() {
        if(!registeViewModel.mPassWord.value!!.checkIsPassword()) return

        if(registeViewModel.mVerificationCode.value.isNullOrBlank()) {
            toast("验证码不能为空")
            return
        }
        if(!registeViewModel.mAgree.get()!!) {
            toast("请勾选协议")
            return
        }

        registeViewModel.requestRegister(RequestRegisterBody(
            dataBinding.tvPhoneNumber.trimProxy(),
            MD5Util.MD5(dataBinding.etPasswordSetting.trimProxy()),
            dataBinding.etVerificationCode.trimProxy(),
            true,
        )){
            requireActivity().resetStartDestination(R.navigation.navigation,R.id.mainFragment)
        }
    }

    /**
     * 发送验证码
     */
    private fun sendVerificationCode() {
        dataBinding.tvPhoneNumber.trimProxy().condition(
                condition = {
                    true
                },
                conform = {
                    registeViewModel.requestVerifyCode(RequestVerifyBody("+${proxyViewModel.itac.value!!}", it)) {
                        dataBinding.etVerificationCode.requestFocus()
                        countDownCoroutines(
                                total = 60,
                                onTick = { tick ->
                                    registeViewModel.run {
                                        mTiming.value = tick
                                        mVerificationCodeText.value = tick.verificationText()
                                        mEnabled.value = enableSendVerificationCode()
                                    }
                                },
                                scope = lifecycleScope
                        )
                    }
                },
                incompatible = {
                    toast(getString(R.string.phone_format_does_not_match))
                })
    }

    private fun showAreaPopupView() {
        CreateXPopupHelper.createBottomAreaCodeListPopupView(PopupViewEntity().apply {
            this.context = requireActivity()
            isShow = true
            itac = proxyViewModel.itac.value!!
            areaCodeList = proxyViewModel.areaCodeEntities.value
            areaCodeListResultCallBack = {
                "+${it.code}".also { area ->
                    dataBinding.tvCountryAreaCode.text = area
                }
                proxyViewModel.itac.value = it.code
                SpUtil.encode(MMKV_ITAC, it.code)
            }
        })
    }

}



